package com.syni.mdd.sjb.common.datatreaure.service.impl.databank.saasminapp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.syni.mdd.sjb.common.component.utils.common.utils.*;
import com.syni.mdd.sjb.common.datatreaure.constants.ResultMsg;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rq.saasminapp.config.*;
import com.syni.mdd.sjb.common.datatreaure.entity.vo.rq.saasminapp.delivery.*;
import com.syni.mdd.sjb.common.datatreaure.service.databank.saasminapp.DeliveryConfigService;
import com.syni.mdd.sjb.common.component.utils.feign.service.mdd.commonuser.UserRestService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Log4j2
public class DeliveryConfigServiceImpl implements DeliveryConfigService {
    @Autowired
    private UserRestService userRestService;

    @Override
    public Map<String, Object> saveDeliverySet(SaveDeliverySetVo saveDeliverySetVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.store.center.service") + "/sys/store/delivery/config/save";
            Map<String,Object> params = BeanUtils.objectToMap(saveDeliverySetVo);
            Map<String, Object> resultMap =postReqMember(postUrl, saveDeliverySetVo.getToken(), saveDeliverySetVo.getUserId(),false,new HashMap<>(), params);
            if(resultMap.get("code") != null && resultMap.get("code").toString().equals("200")){
                return ResultMapHelper.success(resultMap.get("data"), ResultMsg.HAND_SUCCESS);
            }else{
                return ResultMapHelper.failure(resultMap.get("msg").toString());
            }
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> getSelfConfig(StoreIdVo storeIdVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.store.center.service") + "/sys/store/delivery/config/self/get";
            Map<String,Object> params = new HashMap<>();
            params.put("storeId", storeIdVo.getStoreId());
            Map<String, Object> resultMap =reqMember(postUrl, storeIdVo.getToken(), storeIdVo.getUserId(), params);
            if(resultMap.get("code") != null && resultMap.get("code").toString().equals("200")){
                return ResultMapHelper.success(resultMap.get("data"), ResultMsg.HAND_SUCCESS);
            }else{
                return ResultMapHelper.failure(resultMap.get("msg").toString());
            }
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> saveSelfConfig(SaveSelfConfigVo saveSelfConfigVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.store.center.service") + "/sys/store/delivery/config/self/save";
            Map<String,Object> params = BeanUtils.objectToMap(saveSelfConfigVo);
            Map<String, Object> resultMap =postReqMember(postUrl, saveSelfConfigVo.getToken(), saveSelfConfigVo.getUserId(),false,new HashMap<>(), params);
            if(resultMap.get("code") != null && resultMap.get("code").toString().equals("200")){
                return ResultMapHelper.success(resultMap.get("data"), ResultMsg.HAND_SUCCESS);
            }else{
                return ResultMapHelper.failure(resultMap.get("msg").toString());
            }
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> getSelfDelivery(StoreIdVo storeIdVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.store.center.service") + "/sys/store/delivery/config/merchant/get";
            Map<String,Object> params = new HashMap<>();
            params.put("storeId", storeIdVo.getStoreId());
            Map<String, Object> resultMap =reqMember(postUrl, storeIdVo.getToken(), storeIdVo.getUserId(), params);
            if(resultMap.get("code") != null && resultMap.get("code").toString().equals("200")){
                return ResultMapHelper.success(resultMap.get("data"), ResultMsg.HAND_SUCCESS);
            }else{
                return ResultMapHelper.failure(resultMap.get("msg").toString());
            }
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> saveSelfDelivery(SaveSelfDeliveryVo saveSelfDeliveryVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.store.center.service") + "/sys/store/delivery/config/merchant/save";
            Map<String,Object> params = BeanUtils.objectToMap(saveSelfDeliveryVo);
            Map<String, Object> resultMap =postReqMember(postUrl, saveSelfDeliveryVo.getToken(), saveSelfDeliveryVo.getUserId(),false,new HashMap<>(), params);
            if(resultMap.get("code") != null && resultMap.get("code").toString().equals("200")){
                return ResultMapHelper.success(resultMap.get("data"), ResultMsg.HAND_SUCCESS);
            }else{
                return ResultMapHelper.failure(resultMap.get("msg").toString());
            }
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> getOutConfig(StoreIdVo storeIdVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.store.center.service") + "/sys/store/delivery/config/logistics/get";
            Map<String,Object> params = new HashMap<>();
            params.put("storeId", storeIdVo.getStoreId());
            Map<String, Object> resultMap =reqMember(postUrl, storeIdVo.getToken(), storeIdVo.getUserId(), params);
            if(resultMap.get("code") != null && resultMap.get("code").toString().equals("200")){
                return ResultMapHelper.success(resultMap.get("data"), ResultMsg.HAND_SUCCESS);
            }else{
                return ResultMapHelper.failure(resultMap.get("msg").toString());
            }
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> saveOutConfig(SaveOutConfigVo saveOutConfigVo) {
        try{
            Map<String,Object> headMap = new HashMap<>();
            headMap.put("storeId",saveOutConfigVo.getStoreId());
            String postUrl = AppConfig.getProperty("saas.dxshapp.store.center.service") + "/sys/store/delivery/config/logistics/save";
            Map<String,Object> params = BeanUtils.objectToMap(saveOutConfigVo);
            Map<String, Object> resultMap =postReqMember(postUrl, saveOutConfigVo.getToken(), saveOutConfigVo.getUserId(),true,headMap, params);
            if(resultMap.get("code") != null && resultMap.get("code").toString().equals("200")){
                return ResultMapHelper.success(resultMap.get("data"), ResultMsg.HAND_SUCCESS);
            }else{
                return ResultMapHelper.failure(resultMap.get("msg").toString());
            }
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> countPostFeeRecord(StoreIdVo storeIdVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.user.service") + "balance/countPostFeeRecord";
            Map<String,Object> params = new HashMap<>();
            params.put("storeId",storeIdVo.getStoreId());
            Map<String, Object> resultMap =postReqMember(postUrl, storeIdVo.getToken(), storeIdVo.getUserId(),true,params,new HashMap<>());
            return resultMap;
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> getPostFeeRecords(StoreIdVo storeIdVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.user.service") + "balance/getPostFeeRecords";
            Map<String,Object> params = new HashMap<>();
            params.put("storeId",storeIdVo.getStoreId());
            Map<String, Object> resultMap =postReqMember(postUrl, storeIdVo.getToken(), storeIdVo.getUserId(),true, params,new HashMap<>());
            return resultMap;
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> postFeeRechargePrepay(PostFeeVo postFeeVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.service") + "dxshApp/pay/postFeeRechargePrepay?amount=" + postFeeVo.getAmount();
            Map<String, Object> resultMap =postReqMember(postUrl, postFeeVo.getToken(), postFeeVo.getUserId(),false,new HashMap<>(), new HashMap<>());
            return resultMap;
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> getDadaBusinessType(StoreIdVo storeIdVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.store.center.service") + "/sys/store/delivery/config/logistics/getDadaBusinessType";
            Map<String,Object> params = new HashMap<>();
            params.put("storeId",storeIdVo.getStoreId());
            Map<String, Object> resultMap =getReqWithHead(postUrl, storeIdVo.getToken(), storeIdVo.getUserId(),true,params, new HashMap<>());
            if(resultMap.get("code") != null && resultMap.get("code").toString().equals("200")){
                return ResultMapHelper.success(resultMap.get("data"), ResultMsg.HAND_SUCCESS);
            }else{
                return ResultMapHelper.failure(resultMap.get("msg").toString());
            }
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }

    @Override
    public Map<String, Object> getDadaCityList(StoreIdVo storeIdVo) {
        try{
            String postUrl = AppConfig.getProperty("saas.dxshapp.store.center.service") + "/sys/store/delivery/config/logistics/getDadaCityList";
            Map<String,Object> params = new HashMap<>();
            params.put("storeId",storeIdVo.getStoreId());
            Map<String, Object> resultMap =getReqWithHead(postUrl, storeIdVo.getToken(), storeIdVo.getUserId(),true,params, new HashMap<>());
            if(resultMap.get("code") != null && resultMap.get("code").toString().equals("200")){
                return ResultMapHelper.success(resultMap.get("data"), ResultMsg.HAND_SUCCESS);
            }else{
                return ResultMapHelper.failure(resultMap.get("msg").toString());
            }
        }catch (Exception e){
            return ResultMapHelper.failure(ResultMsg.HAND_FAIL);
        }
    }


    public Map<String,Object> reqMember(String requestUrl,String token,Integer userId,Map<String,Object> params){
        Map<String,Object> resultMap = null;
        try {
            RpcResponseVo rpcResponseVo = userRestService.getMiniTokenByUserId_v2(userId,token);
            log.info("=====rpcResponseVo======" + rpcResponseVo);
            if(rpcResponseVo.isSuccess()){
                String minitoken = rpcResponseVo.getData().toString();
                String reponseBody = RestTemplateUtils.getForEntityWithHead(requestUrl,params,RestTemplateUtils.getSassHeader(minitoken));
                resultMap = JSON.parseObject(reponseBody,Map.class);
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return resultMap;
    }

    public Map<String,Object> getReqWithHead(String requestUrl,String token,Integer userId,Boolean isExtra,Map<String,Object> extraMap,Map<String,Object> params){
        Map<String,Object> resultMap = null;
        try {
            RpcResponseVo rpcResponseVo = userRestService.getMiniTokenByUserId_v2(userId,token);
            log.info("=====rpcResponseVo======" + rpcResponseVo);
            if(rpcResponseVo.isSuccess()){
                String minitoken = rpcResponseVo.getData().toString();
                Map<String, Object> saasHeader = RestTemplateUtils.getSassHeader(minitoken);
                if(isExtra){
                    saasHeader.putAll(extraMap);
                }
                String reponseBody = RestTemplateUtils.getForEntityWithHead(requestUrl,params,saasHeader);
                resultMap = JSON.parseObject(reponseBody,Map.class);
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return resultMap;
    }

    public Map<String,Object> postReqMember(String requestUrl,String token,Integer userId,
                                Boolean isExtra,Map<String,Object> extraMap,Map<String,Object> params){
        Map<String,Object> resultMap = null;
        try {
            RpcResponseVo rpcResponseVo = userRestService.getMiniTokenByUserId_v2(userId,token);
            log.info("=====rpcResponseVo======" + rpcResponseVo);
            if(rpcResponseVo.isSuccess()){
                String minitoken = rpcResponseVo.getData().toString();
                Map<String, Object> saasHeader = RestTemplateUtils.getSassHeader(minitoken);
                if(isExtra){
                    saasHeader.putAll(extraMap);
                }
                String reponseBody = RestTemplateUtils.postForEntityForJsonByLoadBalanced(requestUrl,params,saasHeader);
                resultMap = JSON.parseObject(reponseBody, Feature.OrderedField);
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return resultMap;
    }

    public Map<String,Object> postFormReqMember(String requestUrl,String token,Integer userId,
                                Boolean isExtra,Map<String,Object> extraMap,Map<String,Object> params){
        Map<String,Object> resultMap = null;
        try {
            RpcResponseVo rpcResponseVo = userRestService.getMiniTokenByUserId_v2(userId,token);
            log.info("=====rpcResponseVo======" + rpcResponseVo);
            if(rpcResponseVo.isSuccess()){
                String minitoken = rpcResponseVo.getData().toString();
                Map<String, Object> saasHeader = RestTemplateUtils.getSassHeader(minitoken);
                if(isExtra){
                    saasHeader.putAll(extraMap);
                }
                String reponseBody = RestTemplateUtils.postForEntity(RestTemplateUtils.getLoadRestTemplate(),requestUrl,params,saasHeader);
                resultMap = JSON.parseObject(reponseBody,Map.class);
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return resultMap;
    }
}
